<template>
	<view class="avatar-upload">
		<view class="avatar-container" @click="selectAvatar">
			<image 
				:src="avatarUrl" 
				class="avatar-image"
				mode="aspectFill"
			/>
			<view class="avatar-overlay">
				<text class="upload-text">点击更换头像</text>
			</view>
		</view>
		
		<!-- 上传进度 -->
		<view v-if="uploading" class="upload-progress">
			<text class="progress-text">上传中...</text>
		</view>
	</view>
</template>

<script>
import { getAvatarUrl, selectAndUploadImage } from '../utils/imageUtils.js';

export default {
	name: 'AvatarUpload',
	props: {
		avatar: {
			type: String,
			default: ''
		},
		gender: {
			type: Number,
			default: 1
		},
		disabled: {
			type: Boolean,
			default: false
		}
	},
	data() {
		return {
			uploading: false
		}
	},
	computed: {
		avatarUrl() {
			return getAvatarUrl(this.avatar, this.gender);
		}
	},
	methods: {
		async selectAvatar() {
			if (this.disabled || this.uploading) {
				return;
			}
			
			try {
				this.uploading = true;
				
				// 选择并上传图片
				const filePath = await selectAndUploadImage('avatar');
				
				// 触发父组件更新
				this.$emit('avatar-changed', filePath);
				
				uni.showToast({
					title: '头像上传成功',
					icon: 'success'
				});
				
			} catch (error) {
				console.error('头像上传失败:', error);
				uni.showToast({
					title: error.message || '上传失败',
					icon: 'none'
				});
			} finally {
				this.uploading = false;
			}
		}
	}
}
</script>

<style scoped>
.avatar-upload {
	display: flex;
	flex-direction: column;
	align-items: center;
}

.avatar-container {
	position: relative;
	width: 120rpx;
	height: 120rpx;
	border-radius: 60rpx;
	overflow: hidden;
	border: 2rpx solid #e0e0e0;
}

.avatar-image {
	width: 100%;
	height: 100%;
}

.avatar-overlay {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: center;
	justify-content: center;
	opacity: 0;
	transition: opacity 0.3s;
}

.avatar-container:active .avatar-overlay {
	opacity: 1;
}

.upload-text {
	color: white;
	font-size: 20rpx;
	text-align: center;
}

.upload-progress {
	margin-top: 20rpx;
}

.progress-text {
	font-size: 24rpx;
	color: #666;
}
</style>
